<?php

namespace app\common\logic;






use app\common\model\shop\Goods;
use app\common\model\shop\Order;
use app\common\utils\Utils;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\ValidateException;
use think\Request;

/**
 * Token接口
 */
class ShopLogic
{

    protected $cartModel;
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;
        $this->cartModel = Db::name('shop_cart');
        $this->orderModel = new Order();
        $this->orderGoodsModel = Db::name('shop_order_goods');
        $this->goodsModel = new Goods();
    }

    /**
     * 从购物车中删除
     */
    //删除
    public function delete($uid = 0)
    {
        $ids = Utils::explodeStr($this->request->param()['ids']);
        try {
            $w['id'] = array('in', $ids);
            $w['user_id'] = $uid;
            $this->cartModel->where($w)->delete();

            return true;
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    //创建单词订单
    public function createOrderOne()
    {
        //商品ID
        $id = input("id/d", 0);
        //商品数量
        $number = input('number/d', 1);
        $goodsDetail = $this->isCheck($id, $number);
        //积分
        $scoreTotal = (int)($goodsDetail['price'] * $number);

        //用户编号
        $data['user_id'] = UID;
        //生成订单号  表前缀 + 时间戳10位 + 微秒3位 + 随机数4位
        $sn = Random::uuid();
        $data['order_no'] = $sn;
        //收货地址
        //支付状态 0未付款 1已付款 2已退款
        $data['pay'] = 0;
        //订单状态： -2=驳回, -1=取消订单,0=未支付,1=已支付,2=已发货,3=已签收,4=退货中,5=已退款
        $data['status'] = 0;
        //支付时间

        //订单创建时间
        $data['createtime'] = time();
        //需支付总积分
        $data['amount'] = $scoreTotal;
        //需支付总款
        Db::startTrans();
        try {
            //创建订单
            $res = $this->orderModel->insert($data);

            $lastid = $this->orderModel->getLastInsID();
            $goods_data['order_id'] = $lastid;
            $goods_data['goods_id'] = $goodsDetail['id'];
            $goods_data['buy_num'] = $number;
            $goods_data['money'] = $goodsDetail['price'];
            $goods_data['goods_name'] = $goodsDetail['name'];
            $goods_data['goods_thumb'] = $goodsDetail['image'];
            $goods_data['createtime'] = time();

            //写入订单商品表
            $this->orderGoodsModel->insert($goods_data);

            //$dec['id'] = $goodsDetail['id'];
            //减少库存
            //$this->goodsModel->where($dec)->setDec('stock', $number);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return $lastid;
    }

    //创建订单（此方法用于创建由购物车提交上来的多商品订单）
    public function createOrder()
    {
        //购物车表编号
        $ids = Utils::explodeStr($this->request->param()['ids']);
        //积分
        $scoreTotal = 0;

        $list = $this->cartModel
            ->alias('cart')
            ->join('__SHOP_GOODS__ goods', 'goods.id = cart.goods_id')
            ->field('cart.*,goods.id as goods_id,goods.price,goods.origin_price,goods.image,goods.name')
            ->where(['cart.id' => ['in', $ids]])->select();
        foreach ($list as $key => $val) {

            $number = (int)$this->request->param("number_" . $val['id']);
            $scoreTotal = $scoreTotal + Utils::processMoney($val['price'], $number, '*');
        }

        //用户编号
        $data['user_id'] = UID;
        //生成订单号  表前缀 + 时间戳10位 + 微秒3位 + 随机数4位
        $sn = Random::uuid();
        $data['order_no'] = $sn;
        //收货地址
        //支付状态 0未付款 1已付款 2已退款
        $data['pay'] = 0;
        //订单状态： -2=驳回, -1=取消订单,0=未支付,1=已支付,2=已发货,3=已签收,4=退货中,5=已退款
        $data['status'] = 0;
        //支付时间
        //$data['paytime'] = time();
        //付款方式，score = 积分付款, weixin = 微信支付 , alipay = 支付宝 , paypal = paypal
        //$data['paytype'] = '';
        //订单创建时间
        $data['createtime'] = time();
        //需支付总积分
        //需支付总款
        $data['amount'] = $scoreTotal;
        $data['province'] = 0;
        $data['area'] = 0;
        $data['detail'] = 0;


        //需支付总款
        Db::startTrans();
        try {
            //创建订单
            $this->orderModel->insert($data);
            $lastid = $this->orderModel->getLastInsID();
            foreach ($list as $k => $v) {
                $numbers = (int)$this->request->param("number_" . $v['id']);
                if ($numbers <= 0) {
                    throw new ValidateException('购买数量不能小于1');
                }

                //从购物车中获取商品信息
                $this->isCheck($v['goods_id'], $numbers); //检车库存
                $order_goods['order_id'] = $lastid;
                $order_goods['goods_id'] = $v['goods_id'];
                $order_goods['buy_num'] = $numbers;
                $order_goods['money'] = $v['price'];
                $order_goods['goods_name'] = $v['name'];
                $order_goods['goods_thumb'] = $v['image'];
                $order_goods['createtime'] = time();
                $this->orderGoodsModel->insert($order_goods);
                Db::commit();
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }


        return $lastid;
    }


    /**
     * @param $id 商品ID
     * @param $number 购买数量
     * return array;
     */

    public function isCheck($id, $number = 0)
    {
        //积分验证
        $info = $this->goodsModel->where("id", $id)->find();

        //库存验证
        if ($info['num'] < 1) {
            throw new ValidateException($info['name'] . '库存不足');
        }


        return $info;
    }

    /**
     * 商品清单确认
     * @param $orderid 订单id
     */
    public function postOrders($orderid, $check = true)
    {
        $w['user_id'] = UID;
        $w['id'] = $orderid;

        //获取默认收获地址

        $order = $this->orderModel
            ->where($w)
            ->find();
        $goods = $this->orderGoodsModel->where('order_id', $orderid)->select();
        foreach ($goods as $k => &$v) {
            $v['image_text'] = cdnurl($v['goods_thumb'], true);
        }
        $order['orderGoods'] = $goods;
        if ($order['address_id']) {
            $address = (new AddressLogic())->detail($order['address_id']);
        } else {
            $address = (new AddressLogic())->getDefault();
        }

        if (!$order) {
            throw new ValidateException('订单不存在');
        } else {
            if ($check == true) {
                if ($order['status'] != 0) {
                    throw new ValidateException('不能重复购买');
                }
            }
        }

        return [
            'address' => $address,
            'order'   => $order
        ];
    }

}
